package com.pan.insist.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pan.insist.dao.TaskCronMapper;
import com.pan.insist.model.TaskCronModel;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 *  动态配置任务执行时间
 * </p>
 *
 * @author kaiji
 * @since 2020/2/7 10:59
 */
@Log4j2
// @Configuration
@EnableScheduling
@Component
public class TriggerTaskExample implements SchedulingConfigurer {

    @Resource
    private TaskCronMapper taskCronMapper;

    // 执行任务
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                () -> log.info("第一个任务"),
                triggerContext -> {
                    TaskCronModel taskOne = taskCronMapper.selectOne(new QueryWrapper<TaskCronModel>().eq("code", "001"));
                    if (taskOne == null) {
                        return null;
                    }
                    return new CronTrigger(taskOne.getCron()).nextExecutionTime(triggerContext);
                }
        );
        taskRegistrar.addTriggerTask(
                () -> log.info("第二个任务"),
                triggerContext -> {
                    TaskCronModel taskTwo = taskCronMapper.selectOne(new QueryWrapper<TaskCronModel>().eq("code", "002"));
                    if (taskTwo == null) {
                        return null;
                    }
                    return new CronTrigger(taskTwo.getCron()).nextExecutionTime(triggerContext);

                }
        );

    }
}
